<template>
  <section class="content">
      <!-- Default box -->
      <div class="box box-primary">
          <div class="box-header with-border">
              <h3 class="box-title">实体奖品</h3>
          </div>
          <div class="box-body">
              <el-table
                  ref="multipleTable"
                  :data="records"
                  tooltip-effect="dark"
                  stripe
                  style="width: 100%">
                  <el-table-column
                  prop="id"
                  label="ID"
                  width="55">
                  </el-table-column>

                  <el-table-column
                  prop="entity.prize_pic"
                  label="图片"
                  width="160">
                    <template slot-scope="scope">                        
                        <img :src="scope.row.entity.prize_pic" style="height: 100px; width: 100px;">
                    </template>
                  </el-table-column>                  

                  <el-table-column
                  prop="name"
                  label="名称"
                  width="200">
                  </el-table-column>

                  <el-table-column
                  prop="entity.business"
                  label="商家"
                  show-overflow-tooltip>
                  </el-table-column>                  

                  <el-table-column
                  prop="probability"
                  label="概率"
                  width="100">
                  </el-table-column> 

                  <el-table-column
                  prop="qty_left"
                  label="剩余数量"
                  width="100">
                  </el-table-column>

                  <el-table-column
                  prop="qty"
                  label="总数量"
                  width="100">
                  </el-table-column>     

                  <el-table-column
                  prop="entity.end"
                  label="有效时间"
                  width="100">
                  </el-table-column>                                                                           

                  <el-table-column
                  fixed="right"
                  label="操作"
                  width="200">
                  <template slot-scope="scope">
                    <el-button
                    size="mini"
                    @click="handleEdit(scope.$index, scope.row)">编辑</el-button>

                    <el-button
                    size="mini"
                    type="danger"
                    @click="handleDelete(scope.$index, scope.row)">删除</el-button>                    
                  </template>
                  </el-table-column>    
              </el-table>
          </div>
          <!-- /.box-body -->
          <div class="box-footer">
              <el-button @click="addFormVisible = true">添加奖品</el-button>    

              <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[5, 10, 20, 30]"
              :page-size="size"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total" class="pull-right">
              </el-pagination>                       
          </div>
          <!-- /.box-footer-->
      </div>
      <!-- /.box -->

    <el-dialog title="编辑奖品" :visible.sync="editFormVisible">

        <el-form ref="editForm" :model="editForm" label-width="80px" label-position="right">
            <el-form-item label="名称">
                <el-input v-model="editForm.name"></el-input>
            </el-form-item>
            <el-form-item label="概率">
                <el-input v-model="editForm.probability"></el-input>
            </el-form-item>
            <el-form-item label="数量">
                <el-input v-model="editForm.qty"></el-input>
            </el-form-item>
            <el-form-item label="图片">
                <el-upload
                name="picture"
                class="avatar-uploader"
                :action="uploadUrl"
                :show-file-list="false"
                :on-success="handlePicSuccess"
                :before-upload="beforePicUpload"
                :headers="headers">
                <img v-if="editForm.entity.prize_pic" :src="editForm.entity.prize_pic" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>

            </el-form-item>

            <el-form-item label="有效时间">
              <el-date-picker
                v-model="editForm.entity.end"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd">
              </el-date-picker>                
            </el-form-item> 

            <el-form-item label="商家">
                <el-input v-model="editForm.entity.business"></el-input>
            </el-form-item>  

            <el-form-item>
                <el-button type="primary" @click="updatePrize">确定</el-button>
                <el-button @click="editFormVisible = false">取消</el-button>
            </el-form-item>                                                                      
        </el-form>  
    </el-dialog>


    <el-dialog title="添加奖品" :visible.sync="addFormVisible">

        <el-form ref="addForm" :model="addForm" label-width="80px" label-position="right">
            <el-form-item label="名称">
                <el-input v-model="addForm.name"></el-input>
            </el-form-item>
            <el-form-item label="概率">
                <el-input v-model="addForm.probability"></el-input>
            </el-form-item>
            <el-form-item label="数量">
                <el-input v-model="addForm.qty"></el-input>
            </el-form-item>
            <el-form-item label="图片">
                <el-upload
                name="picture"
                class="avatar-uploader"
                :action="uploadUrl"
                :show-file-list="false"
                :on-success="handleAddPrizePicSuccess"
                :before-upload="beforePicUpload"
                :headers="headers">
                <img v-if="addForm.entity.prize_pic" :src="addForm.entity.prize_pic" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>

            </el-form-item>

            <el-form-item label="有效时间">
              <el-date-picker
                v-model="addForm.entity.end"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd">
              </el-date-picker>                
            </el-form-item> 

            <el-form-item label="商家">
                <el-input v-model="addForm.entity.business"></el-input>
            </el-form-item>  

            <el-form-item>
                <el-button type="primary" @click="addPrize">确定</el-button>
                <el-button @click="addFormVisible = false">取消</el-button>
            </el-form-item>                                                                      
        </el-form>  
    </el-dialog>    
  </section>

</template>


<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>


<script>
import * as API from "../../../Consts/Api";
import * as APP from "@/constants/app";

export default {
  data() {
    return {
      headers: {
        Token: this.$storage.get("user").token,
        Version: APP.VERSION
      },

      records: [],

      // 分页
      total: 0,
      size: 5,
      currentPage: 1,

      // 编辑
      editFormVisible: false,
      editForm: {
        activity_id: this.$route.params.id,
        id: "",
        name: "",
        probability: "",
        qty: "",
        type: "entity",
        entity: {
          prize_pic: "",
          business: "",
          end: ""
        }
      },
      // 添加
      addFormVisible: false,
      addForm: {
        activity_id: this.$route.params.id,
        id: "",
        name: "",
        probability: "",
        qty: "",
        type: "entity",
        entity: {
          prize_pic: "",
          business: "",
          end: '',
        }
      },
      // 图片上传
      uploadUrl: API.RED_PACKET_UPLOADS,
    };
  },

  created: function() {
    this.loadData(this.currentPage);

    this.interval = setInterval(() => { 
        this.loadData(this.currentPage);
    }, 2000)    
  },

  beforeDestroy: function() {
    clearInterval(this.interval)
  }, 

  methods: {
    loadData(page) {
      const options = {
        params: {
          per_page: this.size,
          page: page >= 1 ? page : 1,
          activity_id: this.$route.params.id,
          type: "entity"
        }
      };

      this.$http.get(API.RED_PACKET_PRIZES, options).then(response => {
        if (response.data.status == "no") {
          this.$message({
            message: response.data.message,
            type: "error",
            duration: 5000
          });
        } else {
          this.records = response.data.data;
          this.total = response.data.total;
        }
      });
    },

    handleSizeChange(size) {
      this.size = size;
      this.loadData();
    },
    handleCurrentChange(page) {
      this.currentPage = page;
      this.loadData(page);
    },

    handleEdit(index, row) {
      this.editFormVisible = true;
      this.editForm = {
        id: row.id,
        name: row.name,
        probability: row.probability,
        qty: row.qty,
        type: row.type,
        entity: {
          prize_pic: row.entity.prize_pic,
          business: row.entity.business,
          end: row.entity.end
        }
      };
    },
    handleDelete(index, row) {
      this.$http
        .delete(
          API.RED_PACKET_PRIZE.bindValue(":id", row.id),
        )
        .then(response => {
          if (response.data.status == "no") {
            this.$message({
              message: response.data.message,
              type: "error",
              duration: 5000
            });
          } else {
            this.$message({
              message: response.data.message,
              type: "success",
              duration: 5000
            });
            this.loadData();
          }
        });
    },

    handlePicSuccess(res, file) {
      this.editForm.entity.prize_pic = res.data.url;
    },

    beforePicUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },

    updatePrize() {
      this.$http
        .put(
          API.RED_PACKET_PRIZE.bindValue(":id", this.editForm.id),
          this.editForm
        )
        .then(response => {
          if (response.data.status == "no") {
            this.$message({
              message: response.data.message,
              type: "error",
              duration: 5000
            });
          } else {
            this.$message({
              message: response.data.message,
              type: "success",
              duration: 5000
            });

            this.editFormVisible = false;
            this.loadData();
          }
        });
    },

    addPrize() {
      this.$http
        .post(
          API.RED_PACKET_PRIZES,
          this.addForm
        )
        .then(response => {
          if (response.data.status == "no") {
            this.$message({
              message: response.data.message,
              type: "error",
              duration: 5000
            });
          } else {
            this.$message({
              message: response.data.message,
              type: "success",
              duration: 5000
            });

            this.addFormVisible = false;
            this.loadData();
          }
        });
    },

    handleAddPrizePicSuccess(res, file) {
      this.addForm.entity.prize_pic = res.data.url;
    },    
  }
};
</script>